package com.zan.zanchat.common.common.event.listener;

import com.zan.zanchat.common.common.event.UserRegisterEvent;
import com.zan.zanchat.common.user.dao.UserDao;
import com.zan.zanchat.common.user.domain.entity.User;
import com.zan.zanchat.common.user.domain.enums.IdempotentEnum;
import com.zan.zanchat.common.user.domain.enums.ItemEnum;
import com.zan.zanchat.common.user.service.IUserBackpackService;
import lombok.SneakyThrows;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @Author Zan
 * @Create 2024/3/17 16:19
 * @Description :
 */
@Component
public class UserRegisterListener {

    @Resource
    private IUserBackpackService userBackpackService;

    @Resource
    private UserDao userDao;

    /**
     * 发送改名卡事件
     * 加个@Async可以变成异步执行
     * 加强版事件@TransactionalEventListener，可以指定在事务的什么时候，之间、之后执行
     */
    @Async // 异步执行
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT) // 事务提交后执行
    public void sendCard(UserRegisterEvent event) throws InterruptedException {
        User user = event.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID, user.getId().toString());
    }

    /**
     * 前十名的注册徽章
     */
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendBadge(UserRegisterEvent event) throws InterruptedException {
        // 前十名和前一百名的注册徽章
        User user = event.getUser();
        int registeredCount = userDao.count();
        if (registeredCount < 10) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP10_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        } else if (registeredCount < 100) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP100_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        }
    }

}
